import datetime

from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse

from .forms import RegisterForm, UserDetailForm
from .models import User, EmailVerifyRecord
from utils.email_send import send_email_code
import time


def register(request):
    redirect_to = request.POST.get('next', request.GET.get('next', ''))
    # 请求为post 表示用户提交注册数据

    if request.method == 'POST':
        form = RegisterForm(request.POST)

        # 验证数据合法性
        if form.is_valid():
            new_user = form.save(commit=False)
            email = request.POST.get('email')
            username = request.POST.get('username')

            same_email_user = User.objects.filter(email=email)

            if (same_email_user):
                message = '该邮箱地址已被注册，请使用别的邮箱！'
                return render(request, 'users/register.html', locals())

            if email.find("@neusoft.edu.cn") != -1:
                identify = "teacher"

            elif email.find("@nou.com.cn") != -1:
                identify = "student"
            else:
                identify = "other"

            new_user.identify = identify

            new_user.is_active = False
            new_user.nickname = username
            # 保存至数据库
            new_user.save()
            # 发送验证邮件
            send_email_code(email=email)

            if redirect_to:
                return redirect(redirect_to)

            else:
                # 注册成功返回首页
                return redirect('/')


    else:
        # 请求不是 POST，表明用户正在访问注册页面，展示一个空的注册表单给用户
        form = RegisterForm()
    return render(request, 'users/register.html', context={'form': form, 'next': redirect_to})


# def login(request):
#     message = request.GET.get('m')
#     user_email = request.POST.get('username')
#     password = request.POST.get('password')
#
#     if user_email and password:
#         if user_email.find("@neusoft.edu.cn") != -1 or user_email.find("@neusoft.edu.cn") != -1:
#             user = User.objects.get(email=user_email)
#         else:
#             user = User.objects.get(username=user_email)
#
#         if user.password == password:
#             login(request, user)
#     return render(request, 'registration/login.html', context={'message': message})


def forget(request):
    message=''
    if request.method == 'POST':
        user_email = request.POST.get('email')
        if User.objects.filter(email=user_email):
            send_email_code(email=user_email,send_type='forget')
            message = "重置链接已发送，注意查收"
        else:
            message = "邮箱不存在"
        # return HttpResponseRedirect(reverse('users:forget'),content=message)
    return render(request, 'registration/forget.html', context={'message': message})



def reset_password(request, reset_code):
    email_records = EmailVerifyRecord.objects.filter(code=reset_code)
    if email_records.count()<1:
        return render(request,"404.html")

    if request.method == 'POST':
        new_password = request.POST.get('newpassword')
        new_password2 = request.POST.get('newpassword2')
        if new_password != new_password2:
            message = "输入的两次密码不同"
        if email_records:
            for record in email_records:
                email = record.email
                user = User.objects.get(email=email)
                user.password = make_password(new_password, None, hasher='pbkdf2_sha256')
                user.save()
                message = "重置成功,请登录！"
            email_records.delete()
    return render(request, 'registration/reset.html',context=locals())

def activeUser(request, active_code):
    email_records = EmailVerifyRecord.objects.filter(code=active_code)
    form = AuthenticationForm()
    if email_records:
        for record in email_records:
            email = record.email
            user = User.objects.get(email=email)
            user.is_active = True
            user.save()
            message = "激活成功,请登录！"
        email_records.delete()
    else:
        return render(request, "404.html")
    return render(request, "registration/login.html", context={'message': message, 'form': form})


def user(request, pk):
    user = User.objects.get(id=pk)
    return render(request, 'users/userinfo.html', context=locals())


@login_required
def setting(request):
    if request.method == 'POST':
        form = UserDetailForm(instance=request.user,
                              data=request.POST,
                              files=request.FILES)
        if form.is_valid():
            form.save()
            message="修改成功！"
    else:
        form = UserDetailForm(instance=request.user)
    return render(request, 'users/setting.html', context=locals())


@login_required
def newpassword(request):
    if request.method != 'POST':
        return render(request, 'users/change_pass.html')
    else:
        user = request.user
        new_password = request.POST.get('newpassword')
        new_password2 = request.POST.get('newpassword2')
        old_password = request.POST.get('oldpassword')
        if new_password != new_password2:
            message = new_password + ' ' + new_password2
        elif check_password(old_password, user.password):
            user.save()
            message = '修改成功'
        else:
            message = '旧密码错误'
    return render(request, 'users/change_pass.html', context=locals())


def notify(request):
    return render(request, 'users/notifaction.html')
